﻿using System;
using System.Drawing;
using System.Web.Mvc;
using SW.Lite.BLL.Master;
using SW.Lite.Infrastructure.Helpers;

namespace SW.Lite.WebSite.Areas.Master.Controllers
{
    /// <summary>
    /// Class LoginController.
    /// </summary>
    public class LoginController : Controller
    {
        /// <summary>
        /// Indexes this instance.
        /// </summary>
        /// <returns>ActionResult.</returns>
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// Indexes the specified user name.
        /// </summary>
        /// <param name="userName">Name of the user.</param>
        /// <param name="password">The password.</param>
        /// <param name="checkCode">The check code.</param>
        /// <param name="returnUrl">The return URL.</param>
        /// <returns>ActionResult.</returns>
        [HttpPost]
        public ActionResult Index(string userName, string password, string checkCode, string returnUrl = "")
        {
            if (Session["CheckCode"] == null)
            {
                ViewBag.LoginError = "验证码错误";
                return View();
            }

            if (!String.Equals(checkCode, Session["CheckCode"].ToString(), StringComparison.CurrentCultureIgnoreCase))
            {
                ViewBag.LoginError = "验证码错误";
                return View();
            }

            var admin = Admin.Single(userName);

            if (admin == null)
            {
                ViewBag.LoginError = "用户不存在";
                return View();
            }

            var inputPassword = SecurityHelper.Instance.EncryptPassword(password, admin.PasswordSalt);
            if (inputPassword == admin.Password)
            {
                Session["AdminID"] = admin.Id;
                admin.LoginCount++;
                admin.LastLoginIP = RequestHelper.Instance.IP();
                admin.LastLoginTime = DateTime.Now;
                if (String.IsNullOrEmpty(returnUrl))
                    return RedirectToAction("Index", "Home");
                return Redirect(returnUrl);
            }
            ViewBag.LoginError = "密码错误";
            return View();
        }

        /// <summary>
        /// Checks the code.
        /// </summary>
        /// <returns>FileResult.</returns>
        public FileResult CheckCode()
        {
            return File(CreateCheckCodeImage(GenerateCheckCode()), "image/png");
        }

        /// <summary>
        /// Logouts this instance.
        /// </summary>
        /// <returns>ActionResult.</returns>
        public ActionResult Logout()
        {
            Session.Clear();
            return RedirectToAction("Index");
        }

        /// <summary>
        /// Generates the check code.
        /// </summary>
        /// <returns>System.String.</returns>
        private string GenerateCheckCode()
        {
            var checkCode = RandomHelper.Instance.RandomString("****");

            Session["CheckCode"] = checkCode;
            return checkCode;
        }

        /// <summary>
        /// Creates the check code image.
        /// </summary>
        /// <param name="checkCode">The check code.</param>
        /// <returns>System.Byte[].</returns>
        private static byte[] CreateCheckCodeImage(string checkCode)
        {
            var image = new Bitmap((int)Math.Ceiling((checkCode.Length * 14f)), 28);
            var g = Graphics.FromImage(image);

            try
            {
                //生成随机生成器
                var random = new Random();
                //清空图片背景色
                g.Clear(Color.White);
                //画图片的背景噪音线
                for (var i = 0; i < 15; i++)
                {
                    var x1 = random.Next(image.Width);
                    var x2 = random.Next(image.Width);
                    var y1 = random.Next(image.Height);
                    var y2 = random.Next(image.Height);

                    g.DrawLine(new Pen(Color.FromArgb(126, 121, 121)), x1, y1, x2, y2);
                }

                var font = new Font("Verdana", 12, (FontStyle.Bold | FontStyle.Italic));
                var brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.White, Color.GreenYellow, 1.2f, true);
                g.DrawString(checkCode, font, brush, 2, 2);

                //画图片的前景噪音点
                for (var i = 0; i < 50; i++)
                {
                    var x = random.Next(image.Width);
                    var y = random.Next(image.Height);

                    image.SetPixel(x, y, Color.FromArgb(random.Next()));
                }

                //画图片的边框线
                //g.DrawRectangle(new Pen(Color.AliceBlue), 0, 0, image.Width - 1, image.Height - 1);
                var ms = new System.IO.MemoryStream();
                image.MakeTransparent(Color.Transparent);
                image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                return ms.ToArray();
            }
            finally
            {
                g.Dispose();
                image.Dispose();
            }
        }
    }
}
